package com.a51integrated.sfs2x;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Random;

import com.smartfoxserver.v2.db.IDBManager;
import com.smartfoxserver.v2.entities.Room;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.variables.*;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.extensions.BaseClientRequestHandler;
import com.smartfoxserver.v2.extensions.ExtensionLogLevel;

public class StoreHighscoreRequestHandler extends BaseClientRequestHandler {

	@Override
	public void handleClientRequest(User player, ISFSObject params) {
		// TODO Auto-generated method stub

		// The user highscores are tracked by the the time a user spends on obtaining the maximum amount of points.
		// If a user is able to achieve a better time (i.e. obtain the maximum amoun of points in less time than he or she did previously),
		// this is stored and maintained in the database.

		// Get the database manager.
		IDBManager dbManager = getParentExtension().getParentZone().getDBManager();
		
		// Create a connection object.
		Connection connection;
		try
		{
			// Grab a connection from the DB mananger.
			connection = dbManager.getConnection();			

			int usertime = params.getInt("timespent");
			String username = player.getName();

			PreparedStatement stmt = connection.prepareStatement("SELECT `highscore` FROM `highscores` WHERE `username`='" + username + "'");
			ResultSet resSet = stmt.executeQuery();
			
			if (!resSet.first())
			{
				// The result set is empty, a new entry must be inserted.
				stmt = connection.prepareStatement("INSERT INTO `highscores` (`username`, `highscore`, `numgamesplayed`) VALUES ('" + username +
												   "', " + usertime + ", 1)");
				int resInt = stmt.executeUpdate();
				if (resInt == 1)
				{
					trace("Inserted new highscore entry for user " + username + " with score " + usertime);
				}
				else if (resInt == 0)
				{
					trace("Did not insert new highscore entry for user " + username);
				}
				else if (resInt > 1)
				{
					trace("Inserted new highscore entry for user " + username + " with score " + usertime + " -- WARNING: Insert affected multiple rows, there may be an error in the database or the code");
				}
			}
			else
			{
				// An entry was found, it can be updated.
				
				// Check whether the new time is better than the previous best, and if it is, update it in the database.
				if (resSet.getInt("highscore") > usertime)
				{					
					stmt = connection.prepareStatement("UPDATE `highscores` SET `highscore`=(highscore + " + usertime +
													   "), `numgamesplayed`=(numgamesplayed + 1) WHERE `username`='" + username + "'");
					int resInt = stmt.executeUpdate();
					if (resInt == 1)
					{
						trace("Updated highscore for user " + username + " to " + usertime);
					}
					else if (resInt == 0)
					{
						trace("Did not update highscore for user " + username);
					}
					else if (resInt > 1)
					{
						trace("Updated highscore for user " + username + " to " + usertime + " -- WARNING: Updated multiple rows, there may be an error in the database or the code");
					}
				}
				else
				{
					// Else, just update the number of played games.
					stmt = connection.prepareStatement("UPDATE `highscores` SET `numgamesplayed`=(numgamesplayed + 1) WHERE `username`='" + username + "'");
				}
			}
			
			connection.close();
		}
		catch(SQLException e)
		{
			trace(ExtensionLogLevel.WARN, "SQL Failed: " + e.toString());
		}
	}

}
